
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE NamedFieldPuns #-}


module EditBox where


import Graphics.Vty
import Graphics.Vty.Widgets.Base
import Graphics.Vty.Widgets.WrappedText


data EditBox = EditBox { front, back :: String }


empty = EditBox "" ""

contents (EditBox{..}) = reverse front ++ back 


resize w h = id


insert c box = box {front = c : front box} 


moveLeft box@(EditBox{front = c:front', back}) = box {front = front', back = c:back}
moveLeft box = box

  
moveRight box@(EditBox{front, back = c:back'}) = box {front = c:front, back = back'}
moveRight box = box

moveToHome box = box {front = "", back = contents box}
moveToEnd  box = box {front = reverse $ contents box, back = ""}


backSpace box@(EditBox{front = c:front'}) = box {front = front'}
backSpace box = box

delete box@(EditBox{back = c:back'}) = box {back = back'}
delete box = box


instance Widget EditBox where
  -- growHorizontal :: w -> Bool
  growHorizontal _ = True

  -- growVertical :: w -> Bool
  growVertical _ = False

  -- primaryAttribute :: w -> Attr
  primaryAttribute _ = def_attr

  -- withAttribute :: w -> Attr -> w
  withAttribute w _ = w

  -- render :: DisplayRegion -> w -> Image
  render rgn box@(EditBox{front, back})
    = render rgn $ case back of 
        c : back' -> text def_attr (reverse front) <++> cursor c <++> text def_attr back' <++> hFill def_attr ' ' 1
        []        -> text def_attr (reverse front) <++> cursor ' ' <++> hFill def_attr ' ' 1
    where
      width = fromIntegral $ region_width rgn
      cursorAttr = current_attr `with_style` reverse_video
      cursor c   = text def_attr [c] `withAttribute` cursorAttr

-- TODO: convert empty lines to hFill's 

